<template>
  <div>
    <div class="title">
      <span>全部门店</span>
      <div>
        <el-button type="primary" v-if="userinfo.rolesId == 5" @click="synchronizeKoubeiShop()">同步口碑门店</el-button>
        <el-button type="primary" :disabled="exxxx" @click="shopExcel"><i class="el-icon-download"></i>导出</el-button>
        <el-button type="primary" v-if="userinfo.rolesId == 5" @click="addmendianBtn()">新增门店</el-button>
        <el-button icon="el-icon-refresh" @click="refresh"></el-button>
      </div>
    </div>
    <div class="container">
      <div class="screeningBox">
        <div class="leftBox">
          <div class="leftitem">
            <!-- <div class="block">
              <el-date-picker v-model="storesinfo.stardate" type="datetime" placeholder="提交起始时间" value-format="yyyy-MM-dd HH:mm:ss"></el-date-picker>
              <el-date-picker v-model="storesinfo.enddate" type="datetime" placeholder="提交结束时间" value-format="yyyy-MM-dd HH:mm:ss"></el-date-picker>
            </div> -->
             <div class="block">
              <el-date-picker
                v-model="date"
                type="datetimerange"
                value-format="yyyy-MM-dd HH:mm:ss"
                :default-time="['00:00:00', '23:59:59']"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期">
              </el-date-picker>
            </div>
          </div>
          <div class="leftitem">
              <el-select v-model="storesinfo.state" placeholder="门店状态">
                <el-option key="ccc" label="动销" value="1"></el-option>
                <el-option key="zzz" label="未动销" value="0"></el-option>
              </el-select>
              <el-input class="merchants" v-model.trim="storesinfo.storesno"  @keyup.enter.native='soso' placeholder="门店名/门店号"></el-input>
          </div>
        </div>
        <div class="rightBox">
          <div class="rightitem">
            <el-input class="merchants" v-if="userinfo.rolesId != 5 &&userinfo.rolesId != 6" v-model.trim="storesinfo.merchantsno"  @keyup.enter.native='soso' placeholder="商户简称/商户名称/商户号"></el-input>
          </div>
          <div class="rightitem" v-if="userinfo.rolesId == 1 || userinfo.rolesId == 2 || userinfo.rolesId == 8 || userinfo.rolesId == 9">
            <el-form label-width="80px">
              <!-- <el-select class="servicename1" v-model="dimension"  placeholder="选择维度" @change="dimension_menu">
                <el-option keys="1" label="一级服务商" :value="2"></el-option>
                <el-option keys="2" label="二级服务商" :value="3"></el-option>
                <el-option keys="2" label="业态" :value="4"></el-option>
                <el-option keys="2" label="商户" :value="5"></el-option>
                <el-option keys="2" label="门店" :value="6"></el-option>
              </el-select> -->
              <el-autocomplete class="servicename" v-model.trim="tagname"  :fetch-suggestions="querySearch_tag" @select="serviceid_tag" placeholder="标签名称" :trigger-on-focus="false"></el-autocomplete>
            </el-form>
          </div>
          <div class="rightitem">
            <el-button icon="el-icon-search" type="primary" @click="soso">搜索</el-button>
            <el-button icon="el-icon-refresh" type="primary" @click="reset">重置</el-button>
          </div>
        </div>
      </div>
      <div class="statistical">
        <div class="statisticalitem">
          <div>总门店数</div>
          <div>
            <span class="red">{{shopnum.total}}</span> 家
          </div>
        </div>
        <div class="statisticalitem">
          <div>动销门店数</div>
          <div>
            <span class="red">{{shopnum.active}}</span> 家
          </div>
        </div>
      </div>
      <div class="tableBox">
        <el-table
          ref="multipleTable"
          :data="merchantarr"
          tooltip-effect="dark"
          style="width: 100%"
          @selection-change="handleSelectionChange"
          stripe
          :header-cell-style="tableHeaderColor"
          v-loading="loading"
        >
           <el-table-column type="index" align="center" label="序号"></el-table-column>
          <el-table-column type="selection"></el-table-column>
          <el-table-column prop="shopNo" align="center" label="门店号"></el-table-column>
          <el-table-column prop="shopName" align="center" label="门店名"></el-table-column>
          <el-table-column prop="merchantNo" align="center" label="商户号"></el-table-column>
          <el-table-column prop="merchantShortName" align="center" label="商户简称"></el-table-column>
          <el-table-column prop="createTime" align="center" label="创建时间"></el-table-column>
          <el-table-column  align="center" label="门店状态">
              <template slot-scope="scope">
              <div type="text" v-if="scope.row.activityStatus == 1" size="small" style="color:green">动销</div>
              <div type="text" v-else-if="scope.row.status == 98" size="small" style="color:red">停用</div>
              <div type="text" v-else class="red" size="small">未动销</div>
            </template>
          </el-table-column>
          <el-table-column fixed="right" align="center" label="操作" width="120">
            <template slot-scope="scope">
              <el-button type="text" size="small" @click="storeinfo(scope.row)">详情</el-button>
              <!-- <el-button type="text" size="small" @click="details(scope.row)">修改</el-button> -->
              <el-button v-if="scope.row.status != 98"  type="text" size="small" @click="shopblockup(scope.row.id)">停用</el-button>
              <el-button v-if="scope.row.status == 98" type="text" size="small" @click="shopopen(scope.row.id)">启用</el-button>
              <el-button type="text" size="small" @click="shopdelete(scope.row.id)">注销</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="pagination">
          <el-pagination
            background
            @current-change="handleCurrentChange"
            @size-change="sizechange"
            :page-size="10"
            layout="total, sizes, prev, pager, next, jumper"
            :total="combined"
            :current-page.sync="cur_page"
          ></el-pagination>
        </div>
      </div>
      <br>
      <br>
      <!-- 门店详情 -->
      <!-- <el-dialog v-dialogDrag title="门店详情" :visible.sync="visible" width="45%" :close-on-click-modal = "false">
        <el-form
          :model="addmendian"
          status-icon
          ref="addmendian"
          label-width="110px"
          class="demo-dynamic"
        >
          <el-form-item :required="true" label="门店名称" >
            <el-input type="text" v-model="addmendian.name" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item :required="true" label="门店地址">
            <el-input type="text" v-model="addmendian.address" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item :required="true" label="门店联系人">
            <el-input type="text" v-model="addmendian.contact" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item :required="true" label="联系人手机号">
            <el-input type="text" v-model="addmendian.contactphone" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="银联终端号">
            <el-input type="text" v-model="addmendian.bank" autocomplete="off"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="visible = false">取消</el-button>
          <el-button type="primary" @click="shopupdate()">确定</el-button>
        </span>
      </el-dialog> -->
       <!-- 新增门店 -->
      <el-dialog v-dialogDrag title="新增门店" :visible.sync="addmendianBox" width="45%" :close-on-click-modal="false">
        <el-form
          :model="addmendians"
          status-icon
          ref="addmendians"
          label-width="110px"
          class="demo-dynamic"
        >
          <el-form-item :required="true" label="门店名称" >
            <el-input type="text" v-model="addmendians.name" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item :required="true" label="门店电话">
            <el-input type="text" v-model="addmendians.phone" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item :required="true" label="门店地址">
            <el-input type="text" v-model="addmendians.address" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item :required="true" label="联系人">
            <el-input type="text" v-model="addmendians.contact" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item :required="true" label="联系人手机号">
            <el-input type="text" v-model="addmendians.contactphone" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="银联终端号">
            <el-input type="text" v-model="addmendians.bank" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="外部门店号">
            <el-input type="text" v-model="addmendians.alias" autocomplete="off"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addmendianBox = false">取消</el-button>
          <el-button type="primary" @click="addshopfun()">确定</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { shop, getTotalShopCount,shopenable, shopupdate,shopdelete,synchronizeKoubeiShop,addshop,getlabelTagList,getDimensionTagList ,shopdeletes,shopExcel} from "@/api/api";
export default {
  name: "baseform",
  data: function() {
    return {
      exxxx:false,
      cur_page: 1,
      cur_size: 10,
      visible:false,
      visibles:false,
      addmendianBox: false,
      loading: true,
      multipleSelection: [],
      merchantarr:[],
      pageCount:"",
      date:"",
      userinfo:"",
      shopnum:{
        total:"",
        active:""
      },
      combined:0,
      storesinfo:{
        stardate:"",
        enddate:"",
        storesno:'',
        merchantsno:'',
        state:"",
      },
      addmendians:{
        name: "",
        phone: "",
        address: "",
        contact: "",
        contactphone: "",
        bank: "",
        alias:""
      },
      addmendian: {
        name: "",
        address: "",
        contact: "",
        contactphone: "",
        bank: "",
        id:""
      },
      dimension:'',//选择维度
      tagname:'',//标签名
      label_all:[],//标签模糊查询
      tagId:''
    };
  },
  created() {
    this.userinfo = JSON.parse(sessionStorage.getItem('userInfo'))
    this.shop()
  },
  mounted() {
  
  },
  methods: {
     //修改thead 背景色
     tableHeaderColor({ row, column, rowIndex, columnIndex }) {
      if (rowIndex === 0) {
        return 'background-color: #F0F0F0;font-weight: 500;font-size:14px;color:#000;'
      }
    },
    onSubmit() {
      this.$message.success("提交成功！");
    },
    renderheader(h, { column, $index }) {
      return h("span", {}, [
        h("span", {}, column.label.split("?")[0]),
        h("br"),
        h("span", {}, column.label.split("?")[1])
      ]);
    },
    // 分页导航
    handleCurrentChange(val) {
      this.cur_page = val;
      this.shop()
       this.$nextTick(() => {
         document.querySelectorAll('.content')[0].scrollTop = '0'
      });
    },
     // 分页数量
    sizechange(val){
      this.cur_size = val
      this.shop()
       
       this.$nextTick(() => {
         document.querySelectorAll('.content')[0].scrollTop = '0'
      });
       
    },

    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    joinmerchantsinfo() {
      this.$router.push({ path: "/merchantsinfo" });
    },
    // 门店列表
    shop(){
       shop({
          page: this.cur_page,
          size: this.cur_size,
          mchKeywords: this.storesinfo.merchantsno,
          keywords: this.storesinfo.storesno,
          startTime: this.date[0],
          finishTime: this.date[1],
          activityStatus: this.storesinfo.state,
          tagId: this.tagId
        }).then(res => {
          // console.log(res);
          if(res.code == 405){
            sessionStorage. removeItem('token')
            this.$router.push('/login');
          }else{
            this.merchantarr = res.data
            this.combined = res.pageInfo.recordCount
            this.pageCount = res.pageInfo.pageCount
            this.loading = false
          }
        });
          // 门店总数
         getTotalShopCount({
          page: this.cur_page,
          size: this.cur_size,
          mchKeywords: this.storesinfo.merchantsno,
          keywords: this.storesinfo.storesno,
          startTime: this.date[0],
          finishTime: this.date[1],
          activityStatus: this.storesinfo.state,
          tagId: this.tagId
        }).then(res => {
          // console.log(res);
          if(res.code == 405){
            sessionStorage. removeItem('token')
            this.$router.push('/login');
          }else{
            this.shopnum = res.data
          }
        });
    },
    // 导出
    shopExcel(){
       this.exxxx = true;
         const loading = this.$loading({
          lock: true,
          text: 'Loading',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
        shopExcel({
           page: this.cur_page,
          size: this.cur_size,
          mchKeywords: this.storesinfo.merchantsno,
          keywords: this.storesinfo.storesno,
          startTime: this.date[0],
          finishTime: this.date[1],
          activityStatus: this.storesinfo.state,
          tagId: this.tagId
        }).then(res => {
          if(res.code == 405){
            sessionStorage. removeItem('token')
            this.$router.push('/login');
             loading.close();
             this.exxxx = false;
          }else if(res.code == 200){
            let elink = document.createElement('a');
            elink.download = "我的商户.xls";
            elink.href = res.data;
            elink.click();
            loading.close();
            this.exxxx = false;
            }
            else{
              this.$message.error(res.message);
              loading.close();
              this.exxxx = false;
            }
          })
    },
    // 搜索
    soso(){
      this.loading =true;
      this.cur_page = 1
      this.shop()
    },
    // 重置
    reset(){
      this.storesinfo.merchantsno = ''
      this.storesinfo.storesno = ''
      this.storesinfo.stardate = ''
      this.storesinfo.enddate = ''
      this.storesinfo.state = ''
      this.cur_page = 1
      this.date = ''
      this.dimension = ''
      this.tagname = ''
      this.tagId = ''
    },
    // 刷新
    refresh (){
      // this.$router.replace({
      //   path: '/refresh',
      //   query: {
      //     t: Date.now()
      //   }
      // })
       this.loading = true
       this.reset()
       this.shop()
    },
    //详情
    // details(val){
    //   this.visible = true
    //   console.log(val)
    //   this.addmendian.name = val.shopName
    //   this.addmendian.address = val.shopAddress
    //   this.addmendian.contact = val.managerName
    //   this.addmendian.contactphone = val.managerMobile
    //   this.addmendian.bank = val.terminalNoUni
    //   this.addmendian.id = val.id
    // },
    // 修改门店
    // shopupdate(){
    //   shopupdate({
    //       shopName:this.addmendian.name,
    //       shopAddress:this.addmendian.address,
    //       managerName:this.addmendian.contact,
    //       managerMobile:this.addmendian.contactphone,
    //       terminalNoUni:this.addmendian.bank,
    //     },this.addmendian.id).then(res => {
    //       console.log(res);
    //       if(res.code == 405){
    //         sessionStorage. removeItem('token')
    //         this.$router.push('/login');
    //       }else{
    //         if(res.code == 200){
    //           this.$message({
    //             message: '修改成功',
    //             type: 'success'
    //           });
    //           this.visible = false
    //           this.refresh()
    //         }else{
    //           this.$message.error(res.message);
    //         }
    //       }
    //     });
    // },
    // 注销门店
    shopdelete(val){
        this.$confirm('是否确定注销？如确定，该门店将被移除', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
         shopdelete({},val).then(res => {
          // console.log(res);
          if(res.code == 405){
            sessionStorage. removeItem('token')
            this.$router.push('/login');
          }else if(res.code == 200){
            this.$message({
            message: '已注销',
            type: 'success'
          });
          this.refresh()
          }else{
            this.$message.error(res.message);
          }
        });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          });          
        });
       
    },
    // 同步口碑门店
    synchronizeKoubeiShop(){
      synchronizeKoubeiShop({
          
        }).then(res => {
          console.log(res);
          if(res.code == 405){
            sessionStorage. removeItem('token')
            this.$router.push('/login');
          }else{
            if(res.code == 200){
              this.$message({
                message: '同步成功',
                type: 'success'
              });
              this.shop()
            }else{
              this.$message.error(res.message);
            }
          }
        });
    },
    // 新增门店box
    addmendianBtn(){
      this.addmendianBox = true
    },
    // 确定新增门店
    // 增加门店
    addshopfun() {
      const loading = this.$loading({
        lock: true,
        text: "Loading",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)"
      });
      addshop({
        merchantId: this.userinfo.fid,
        shopName: this.addmendians.name,
        shopTel: this.addmendians.phone,
        shopAddress: this.addmendians.address,
        managerName: this.addmendians.contact,
        managerMobile: this.addmendians.contactphone,
        terminalNoUni: this.addmendians.bank,
        userId : 1,
        alias: this.addmendians.alias,
        instno: sessionStorage.getItem("instNo"),
        key: sessionStorage.getItem("key")
      }).then(res => {
        if (res.code == 200) {
          loading.close();
          this.$message({
            message: "新增成功",
            type: "success"
          });
          this.addmendianBox = false;
          this.refresh();
        } else {
          this.$message.error(res.message);
          loading.close();
        }
        if (res.code == 405) {
          sessionStorage.removeItem("token");
          this.$router.push("/login");
        } else {
        }
      });
    },
    //门店详情
    storeinfo(val) {
      // console.log(val)
      this.$router.push({ 
        path: "/storesinfo"
      });
      sessionStorage.setItem('store_id',JSON.stringify(val.id))
      sessionStorage.setItem('store_shopName',JSON.stringify(val.shopName))
      sessionStorage.setItem('store',JSON.stringify(val))
    },
    //维度查询标签
    // dimension_menu(v){
    //   this.label_all = []
    //   getDimensionTagList({
    //     roleId: v
    //   }).then(res => {
    //     if(res.code == 405){
    //       sessionStorage. removeItem('token')
    //       this.$router.push('/login');
    //     }else if(res.code == 200){
    //       for(var i=0;i<res.data.length;i++){
    //         this.label_all.push({'value':res.data[i].tagName,'id':res.data[i].tagId})
    //       }
    //     }else{
    //       this.$message.error(res.message);
    //     }
    //   })
    // },
    //标签模糊
    querySearch_tag(queryString,cb){
      let that = this
      getDimensionTagList({
        roleId: 6,
        tagwords: this.tagname
      }).then(res => {
        if(res.code == 405){
          sessionStorage. removeItem('token')
          that.$router.push('/login');
        }else if(res.code == 200){
          that.label_all = []
          for(var i=0;i<res.data.length;i++){
            that.label_all.push({'value':res.data[i].tagName,'id':res.data[i].tagId})
          }
          let servicearr = that.label_all;
          let results = queryString
            ? servicearr.filter(that.createFilter(queryString))
            : servicearr;
          // 调用 callback 返回建议列表的数据
          cb(results);
        }else{
          that.$message.error(res.message);
        }
      })
    },
    serviceid_tag(item){
      console.log(item)
      this.tagId = item.id
    },
    createFilter(queryString) {
      return restaurant => {
        return (
          restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) !==
          -1
        );
      };
    },
    // 停用门店
    shopblockup(id){
      this.$confirm('是否确定停用？如确定，该门店将被停用', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
         shopdeletes({},id).then(res => {
          // console.log(res);
          if(res.code == 405){
            sessionStorage. removeItem('token')
            this.$router.push('/login');
          }else if(res.code == 200){
            this.$message({
            message: '已停用',
            type: 'success'
          });
          this.refresh()
          }else{
            this.$message.error(res.message);
          }
        });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          });          
        });
    },
    // 启用门店
    shopopen(id){
      shopenable({
        },id).then(res => {
          console.log(res);
          if(res.code == 405){
            sessionStorage. removeItem('token')
            this.$router.push('/login');
          }else{
            if(res.code == 200){
              this.$message({
                message: '启用成功',
                type: 'success'
              });
              this.visible = false
              this.refresh()
            }else{
              this.$message.error(res.message);
            }
          }
        });
    }
  }
};
</script>
<style scoped lang="less">
.title {
  background: #fff;
  padding: 10px 10px;
  font-size: 18px;
  font-weight: 500;
  display: flex;
  justify-content: space-between;
}
.name {
  width: 25%;
}
.screeningBox {
  width: 100%;
  display: flex;
}
.leftBox,
.rightBox {
  width: 50%;
  padding: 0 15px;
  box-sizing: border-box;
}
.leftBox > .leftitem {
  margin-bottom: 15px;
}
.rightBox > .rightitem {
  margin-bottom: 15px;
}
.merchants {
  width: 50%;
}
.statistical {
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  background: #374459;
  color: #fff;
  padding: 12px;
  box-sizing: border-box;
}
.statistical > .statisticalitem {
  width: 50%;
  text-align: center;
  line-height: 200%;
}
.tableBox {
  margin-top: 20px;
}

.red {
  color: #f9607d;
}

.my-autocomplete {
  li {
    line-height: normal;
    padding: 7px;

    .name {
      text-overflow: ellipsis;
      overflow: hidden;
    }
    .addr {
      font-size: 12px;
      color: #b4b4b4;
    }

    .highlighted .addr {
      color: #ddd;
    }
  }
}
.servicename{
  width: 50%;
}
</style>